<template>
  <div class="flex flex-col px-4 pt-4">
    <div>
      <template v-if="type === 'String'">
        <div class="flex flex-row items-center gap-2 text-sm mb-2">
          <p v-if="required" class="text-red-600">*</p>
          <p>{{ title }}</p>
        </div>
        <van-field
          :placeholder="placeholder"
          v-model="inputValue"
          :error-message="error"
          :required="required"
          :error-message-align="'left'"
          @blur="validateInput"
        >
          <template #input v-if="autocomplete">
            <el-autocomplete
              ref="autocompleteRef"
              class="form-autocomplete w-full"
              placement="bottom-start"
              v-model="inputValue"
              clearable
              :debounce="300"
              :fetch-suggestions="querySearchName"
              :placeholder="placeholder"
              @blur="autocompleteRef?.close()"
              @select="handleSelectSuggestions"
            />
          </template>
        </van-field>
      </template>

      <template v-else-if="type === 'TextArea'">
        <div class="flex flex-row items-center gap-2 text-sm mb-2">
          <p v-if="required" class="text-red-600">*</p>
          <p>{{ title }}</p>
        </div>
        <van-field
          v-model="inputValue"
          type="textarea"
          :required="required"
          :maxlength="maxlength"
          :placeholder="placeholder"
          :error-message="error"
          :error-message-align="'left'"
          rows="3"
          autosize
          show-word-limit
          @blur="validateInput"
        />
      </template>

      <template v-else-if="type === 'DateTime'">
        <div class="flex flex-row items-center gap-2 text-sm mb-2">
          <p v-if="required" class="text-red-600">*</p>
          <p>{{ title }}</p>
        </div>
        <van-field
          v-model="inputValue"
          readonly
          :required="required"
          :error-message="error"
          :placeholder="placeholder"
          :error-message-align="'left'"
          @click="showDatetimePicker = true"
        />
        <van-popup v-model:show="showDatetimePicker" position="bottom">
          <van-picker-group
            @confirm="onDatetimeConfirm"
            :show-toolbar="true"
            :tabs="['选择日期', '选择时间']"
          >
            <van-date-picker v-model="tempDateArray" :min-date="new Date()" />
            <van-time-picker v-model="tempTimeArray" />
          </van-picker-group>
        </van-popup>
      </template>

      <template v-else-if="type === 'Date'">
        <div class="flex flex-row items-center gap-2 text-sm mb-2">
          <p v-if="required" class="text-red-600">*</p>
          <p>{{ title }}</p>
        </div>
        <van-field
          v-model="inputValue"
          readonly
          :required="required"
          :error-message="error"
          :error-message-align="'left'"
          :placeholder="placeholder"
          @click="showDatePicker = true"
        />
        <van-popup v-model:show="showDatePicker" position="bottom">
          <van-date-picker
            v-model="tempDateArray"
            @confirm="onDateConfirm"
            @cancel="showDatePicker = false"
          />
        </van-popup>
      </template>

      <template v-else-if="type === 'MultiSelectPeople'">
        <div class="flex flex-row items-center gap-2 text-sm mb-2">
          <p v-if="required" class="text-red-600">*</p>
          <p>{{ title }}</p>
        </div>
        <van-field
          readonly
          :required="required"
          :error-message="error"
          :error-message-align="'left'"
          :placeholder="placeholder"
          is-link
          @click="showPeoplePicker = true"
        >
          <template v-slot:input>
            <div
              v-if="peopleList?.length > 0"
              class="flex flex-row flex-wrap items-center gap-2 text-sm mb-2"
            >
              <div
                class="flex flex-row items-center gap-2 bg-gray-100 px-2 py-1 text-nowrap rounded-md"
                v-for="people in peopleList"
                :key="people.id"
              >
                <p>{{ people.name }}</p>
                <!--                TODO: 组件需要支持同步更改-->
<!--                                <van-icon name="cross" @click="onRemovePeople(people)" />-->
              </div>
            </div>
            <div v-else class="text-sm text-gray-400">
              {{ placeholder }}
            </div>
          </template>
        </van-field>
        <van-popup v-model:show="showPeoplePicker" position="bottom"  teleport="body"   :style="{ height: '90%' }" >
          <choosePeopleView
            v-if="showPeoplePicker"
            :default-selected-items="peopleList"
            :defaultSelectedSelf="!haveConfirmPeople"
            :enableCache="true"
            @confirm="onConfirmPeople"
            dprt-area="allDprt" />
        </van-popup>
      </template>

      <template v-else-if="type === 'Integer'">
        <div class="flex flex-row items-center gap-2 text-sm mb-2">
          <p v-if="required" class="text-red-600">*</p>
          <p>{{ title }}</p>
        </div>
        <van-field
          v-model="inputValue"
          type="digit"
          :required="required"
          :error-message="error"
          :error-message-align="'left'"
          @blur="validateInput"
        />
      </template>

      <template v-else-if="type === 'Select'">
        <span class="ml-4 mb-2 text-sm">
          <span v-if="required" class="text-red-600">*</span>
          {{ title }}(单选)
        </span>
        <van-radio-group v-model="inputValue" @change="validateInput">
          <van-cell-group inset>
            <van-cell
              v-for="option in options"
              :key="option.value"
              :title="option.label"
              clickable
              @click.stop="toggleRadio(option.value)"
            >
              <template #right-icon>
                <van-radio @click="() => {}" :name="option.value" />
              </template>
            </van-cell>
          </van-cell-group>
        </van-radio-group>
      </template>

      <template v-else-if="type === 'MultiSelect'">
        <span class="ml-4 mb-2 text-sm">
          <span v-if="required" class="text-red-600">*</span>
          {{ title }}(多选)
        </span>
        <van-checkbox-group v-model="inputValue" @change="validateInput">
          <van-cell-group inset>
            <van-cell
              v-for="option in options"
              :key="option.value"
              :title="option.label"
              clickable
              @click.stop="toggleCheckbox(option.value)"
            >
              <template #right-icon>
                <van-checkbox @click.stop="() => {}" :name="option.value" />
              </template>
            </van-cell>
          </van-cell-group>
        </van-checkbox-group>
      </template>
      <template v-else-if="type === 'Divider'">
        <div class="flex flex-row items-center gap-2">
          <div class="w-[4px] rounded-md h-[16px] bg-yxt-blue"></div>
          <h5 class="text-sm font-bold">{{ title }}</h5>
        </div>
      </template>
    </div>

    <div
      v-if="error && (type === 'Select' || type === 'MultiSelect')"
      class="error-message"
    >
      {{ error }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from "vue";
import dayjs from "dayjs";

export interface Option {
  label: string;
  value: string | number;
}

interface PeopleModel {
  id: string;
  name: string;
}

interface Props {
  type:
    | "String"
    | "TextArea"
    | "DateTime"
    | "Date"
    | "Integer"
    | "Select"
    | "MultiSelect"
    | "Divider"
    | "MultiSelectPeople";
  options?: Option[];
  // validate?: (value: any) => string  | undefined;
  modelValue?: any;
  title?: string;
  placeholder?: string;
  maxlength?: number;
  required?: boolean;
  autocomplete?: boolean;
  querySearchName?: Function;
}

const props = withDefaults(defineProps<Props>(), {
  options: () => [],
  placeholder: () => "请输入内容",
  maxlength: () => 100,
  required: false,
  validate: undefined,
  modelValue: undefined,
  autocomplete: false,
});

const emit = defineEmits(["update:modelValue", "onSelectSuggestions"]);

onMounted(() => {
  setTimeout(() => {
    inputValue.value = props.modelValue;
    if (props.type === "MultiSelectPeople") {
      peopleList.value = inputValue.value || [];
    }
    console.log("input value :", inputValue.value);
  }, 200);
});

const autocompleteRef = ref(null);

function handleSelectSuggestions() {
  emit("onSelectSuggestions", inputValue.value);
}

// 输入值
const inputValue = ref(props.modelValue);
const error = ref("");

// 选择人员相关
const showSelectPeople = ref(true);

// 日期时间选择相关
const showDatetimePicker = ref(false);
const tempDatetimeValue = ref<string>(dayjs().format("YYYY-MM-DD HH:mm"));
const showDatePicker = ref(false);

const tempDateArray = ref<[string, string, string]>([
  dayjs().format("YYYY"),
  dayjs().format("MM"),
  dayjs().format("DD"),
]);

const tempTimeArray = ref<[string, string]>([dayjs().format("HH"), dayjs().format("mm")]);

// 监听输入值变化
watch(inputValue, (newVal) => {
  console.log("watch: ", newVal);
  emit("update:modelValue", newVal);
});

// 选择人员
const showPeoplePicker = ref(false);
const peopleList = ref<Array<PeopleModel>>([]);
const haveConfirmPeople = ref(false);
function onConfirmPeople(arr: Array<PeopleModel>) {
  arr = arr.map((v: PeopleModel) => {
    return { id: v.id, name: v.name };
  });
  console.log("onConfirmPeople", arr);
  peopleList.value = arr || [];
  showPeoplePicker.value = false;
  inputValue.value = arr;
  haveConfirmPeople.value = true;
}

// function onRemovePeople(people) {
//   peopleList.value = peopleList.value.filter(v => v !== people)
// }

// 默认校验函数
const defaultValidate = (value: any): string | undefined => {
  if (props.type === "TextArea") {
    return undefined;
  }

  if (props.type === "Select" || props.type === "MultiSelect") {
    if (Array.isArray(value) && value.length === 0) {
      return "请至少选择一个选项";
    }
    if (!value) {
      return "请选择一个选项";
    }
    return undefined;
  }

  if (!value && value !== 0) {
    return "此项不能为空";
  }

  if (props.type === "Integer") {
    const num = Number(value);
    if (!Number.isInteger(num) || isNaN(num)) {
      return "请输入有效的整数";
    }
  }

  return undefined;
};

// 校验输入
const validateInput = () => {
  if (props.validate) {
    error.value = props.validate(inputValue.value) || "";
  } else {
    error.value = defaultValidate(inputValue.value) || "";
  }
};

// 日期时间选择确认
const onDatetimeConfirm = (value: string) => {
  inputValue.value = tempDateArray.value.join("-") + " " + tempTimeArray.value.join(":");
  showDatetimePicker.value = false;
  validateInput();
};

// 日期选择确认
const onDateConfirm = (values: object[]) => {
  inputValue.value = values.selectedValues.join("-");
  showDatePicker.value = false;
  validateInput();
};

// 切换多选框
const toggleCheckbox = (value: string | number) => {
  const index = inputValue.value?.indexOf(value) ?? -1;
  console.log("toggleCheckbox: ", inputValue.value, value, index);
  if (index === -1) {
    inputValue.value = [...(inputValue.value || []), value];
  } else {
    inputValue.value = inputValue.value.filter((v: any) => v !== value);
  }
};


const toggleRadio = (value: string | number) => {
  inputValue.value = value;
}
</script>

<style scoped lang="less">

</style>
